import 'package:dio/dio.dart';
import 'base_data.dart';

// 自定义响应类
class CustomResponse<T extends BaseData> {
  /// 原始响应
  /// [Response] 是 Dio 的响应类，包含了请求的所有信息
  ///
  final Response originalResponse;

  /// 响应状态码
  /// [code] 是服务器返回的状态码，通常是 200 表示成功
  final int code;

  /// 响应消息
  /// [message] 是服务器返回的消息，通常是描述请求结果的字符串
  final String message;

  /// 响应数据
  /// [data] 是服务器返回的单个数据对象，类型为 [T]
  final T? data;

  /// 响应数据列表
  /// [listData] 是服务器返回的数据列表，类型为 [List<T>]
  final List<T>? listData;

  /// 响应是否成功
  bool get isSuccess => code == 0;

  CustomResponse({
    required this.originalResponse,
    required this.code,
    required this.message,
    this.data,
    this.listData,
  });

  // 自动转换单个模型
  factory CustomResponse.fromJson(
    Response response,
    T Function(Map<String, dynamic>) fromJson,
  ) {
    final json = response.data as Map<String, dynamic>;
    final dataJson = json['data'];
    return CustomResponse<T>(
      originalResponse: response,
      code: json['code'] as int,
      message: json['message'] as String,
      data: (dataJson is Map<String, dynamic>) ? fromJson(dataJson) : null,
      listData:
          (dataJson is List) ? dataJson.map((e) => fromJson(e)).toList() : null,
    );
  }

  @override
  String toString() {
    return 'CustomResponse{code: $code, message: $message, data: $data, listData: $listData}';
  }
}
